package com.chuangjiangx.member.manager.web.web.stored.controller;


import com.chuangjiangx.commons.page.PagingResult;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.domain.shared.model.PayEntry;
import com.chuangjiangx.member.manager.basic.web.controller.BaseController;
import com.chuangjiangx.member.manager.basic.web.interceptor.Login;
import com.chuangjiangx.member.manager.common.Constants;
import com.chuangjiangx.member.manager.common.RequestHeadersUtil;
import com.chuangjiangx.member.manager.common.ThreadLocalUser;
import com.chuangjiangx.member.manager.common.utils.StrUtils;
import com.chuangjiangx.member.manager.web.web.stored.request.MbrConsumeRecordRequest;
import com.chuangjiangx.member.manager.web.web.stored.response.MbrOrderDetailResponse;
import com.chuangjiangx.member.manager.web.web.stored.response.MbrOrderListResponse;
import com.chuangjiangx.member.stored.ddd.dal.condition.MbrOrderListCondition;
import com.chuangjiangx.member.stored.ddd.dal.dto.MbrOrderDetail;
import com.chuangjiangx.member.stored.ddd.dal.dto.MbrOrderList;
import com.chuangjiangx.member.stored.ddd.domain.model.MbrOrderStatus;
import com.chuangjiangx.member.stored.ddd.domain.model.MbrOrderType;
import com.chuangjiangx.member.stored.ddd.query.MbrOrderQuery;
import com.sun.jmx.snmp.ThreadContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会员消费记录 v3-1
 */
@RestController
@Api(value = "MbrOrderController", tags = "会员消费记录列表")
@RequestMapping(value = "/api/mbr/order", produces = "application/json;charset=UTF-8")
public class MbrOrderController extends BaseController {

    @Autowired
    private MbrOrderQuery mbrOrderQuery;



    /**
     * 加载记录列表
     * @param request 参数
     * @return com.chuangjiangx.commons.response.CamelResponse
     * @see MbrOrderListResponse
     */
    @RequestMapping(value = "/consumer-list")
    @ApiOperation(value = "加载会员消费记录")
    @Login
    public Response consumerList(@Validated MbrConsumeRecordRequest request) {

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        MbrOrderListCondition condition = new MbrOrderListCondition();
        condition.setOrderNumber(request.getOrderNumber());
        condition.setMobile(request.getMobile());
        condition.setStoreId(request.getStoreId());
        condition.setStartTime(request.getStartTime());
        condition.setEndTime(request.getEndTime());
        condition.setType(MbrOrderType.CONSUME.value);

        condition.setMerchantId(user.getMerchantId());
        condition.setPageNumber(request.getPage().getPageNO());
        condition.setPageSize(request.getPage().getEveryPageCount());
        condition.setStoreUserId(user.getStoreUserId());
        condition.setStoreUserName(request.getStoreUserName());
        condition.setPayEntry(request.getPayEntry());
        condition.setPayStatus(request.getStatus());
        PagingResult<MbrOrderList> result = mbrOrderQuery.webMbrOrderList(condition);
        result.getItems()
                .forEach(s -> {
                    s.setMobile(StrUtils.encodeMobilePhone(s.getMobile()));
                });
        return ResponseUtils.successCamel(result);
    }

    /**
     * 会员消费记录 导出
     */
    @RequestMapping(value = "/export/consumer-list", produces = "application/json")
    @Login
    @ApiOperation(value = "会员消费记录导出")
    public void exportConsumerList(HttpServletResponse response, HttpServletRequest request) throws IOException, ParseException {

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);

        //封装获取参数
        MbrOrderListCondition condition = new MbrOrderListCondition();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String storeUserName = request.getParameter("storeUserName");
        condition.setOrderNumber(request.getParameter("orderNumber"));
        condition.setMobile(request.getParameter("mobile"));
        if(!StringUtils.isEmpty(request.getParameter("storeId"))){
            condition.setStoreId(Long.valueOf(request.getParameter("storeId")));
        }
        if(!StringUtils.isEmpty(startTime)){
            condition.setStartTime(sdf.parse(startTime));
        }
        if(!StringUtils.isEmpty(endTime)){
            condition.setEndTime(sdf.parse(endTime));
        }
        if (!StringUtils.isEmpty(storeUserName)) {
            condition.setStoreUserName(storeUserName);
        }
        condition.setType(MbrOrderType.CONSUME.value);

        condition.setMerchantId(user.getMerchantId());
        condition.setPageNumber(Integer.valueOf(request.getParameter("pageNO")));
        condition.setPageSize(Integer.valueOf(EXPORT_SIZE));
        condition.setStoreUserId(user.getStoreUserId());
        String payEntry = request.getParameter("payEntry");
        condition.setPayEntry(StringUtils.isBlank(payEntry) ? null : Integer.valueOf(payEntry));

        //生成模板
        OutputStream out = response.getOutputStream();
        RequestHeadersUtil.exportRequestHeader(response, "会员消费记录");

        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try {
            PagingResult<MbrOrderList> result = mbrOrderQuery.webMbrOrderList(condition);
            List<MbrOrderList> mbrOrderLists = new ArrayList<>();
            result.getItems().forEach(mbrOrder -> {
                mbrOrder.setMobile(StrUtils.encodeMobilePhone(mbrOrder.getMobile()));
                mbrOrderLists.add(mbrOrder);
            });

            osw = new OutputStreamWriter(out, "GBK");
            bw = new BufferedWriter(osw);
            bw.append("序号").append(",")
                    .append("交易单号").append(",")
                    .append("手机号").append(",")
                    .append("消费金额").append(",")
                    .append("会员优惠").append(",")
                    .append("扣款金额").append(",")
                    .append("支付状态").append(",")
                    .append("支付方式").append(",")
                    .append("交易门店").append(",")
                    .append("门店店员").append(",")
                    .append("\r");
            if (!mbrOrderLists.isEmpty()) {
                int myOrderListSize = mbrOrderLists.size();
                for(int item = 0;item < myOrderListSize;item ++){
                    MbrOrderList mbrOrder = mbrOrderLists.get(item);
                    bw.append(String.valueOf( item + 1)).append(",")
                            .append(StringUtils.isEmpty(mbrOrder.getOrderNumber())?"":getCompleteExcelString(mbrOrder.getOrderNumber())).append(",")
                            .append(StringUtils.isEmpty(mbrOrder.getMobile())?"":mbrOrder.getMobile()).append(",")
                            .append(mbrOrder.getOrderAmount()!=null?String.valueOf(mbrOrder.getOrderAmount()):"").append(",")
                            .append(StringUtils.isEmpty(String.valueOf(mbrOrder.getDiscountAmount()))?"":String.valueOf(mbrOrder.getDiscountAmount())).append(",")
                            .append(mbrOrder.getPaidAmount()!=null?String.valueOf(mbrOrder.getPaidAmount()):"").append(",")
                            .append((mbrOrder.getStatus()!=null?MbrOrderStatus.of(mbrOrder.getStatus()).name:"")).append(",")
                            .append(mbrOrder.getPayEntry()!=null?PayEntry.getPayEntry(mbrOrder.getPayEntry()).name:"").append(",")
                            .append(mbrOrder.getStoreName()).append(",")
                            .append(StringUtils.isEmpty(mbrOrder.getStoreUserName()) ? "" : mbrOrder.getStoreUserName()).append(",")
                            .append("\r");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                bw.close();
            }
            if (osw != null) {
                osw.close();
            }
            if (out != null) {
                out.close();
            }
        }

    }




    /**
     * 获取消费记录详情
     * @param mbrOrderId 会员消费订单id
     * @return com.chuangjiangx.commons.response.CamelResponse
     * @see MbrOrderDetailResponse
     */
    @RequestMapping(value = "/order-detail")
    @Login
    public Response orderDetail(Long mbrOrderId) {
        MbrOrderDetail detail = mbrOrderQuery.mbrOrderDetail(mbrOrderId);
        return ResponseUtils.successCamel(detail);
    }

    @RequestMapping(value = "/order-payEntry")
    @Login
    public Response orderPayEntry() {
        List<Map<String, String>> result = new ArrayList<>();
        for (PayEntry payEntry : PayEntry.values()) {
            if (payEntry.value == -1) {
                continue;
            }
            Map<String, String> data = new HashMap<>();
            data.put("name", payEntry.name);
            data.put("value", payEntry.value + "");
            result.add(data);
        }
        return ResponseUtils.success(result);
    }

}
